package org.bjf.modules.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bjf.cache.CacheNameConfig.RedisCacheEnum.Names;
import org.bjf.modules.core.service.BaseService;
import org.bjf.modules.sys.bean.SysRole;
import org.bjf.modules.sys.bean.SysUserRole;
import org.bjf.modules.sys.mapper.SysRoleMapper;
import org.bjf.modules.sys.query.SysRoleQuery;
import org.bjf.modules.sys.query.SysUserRoleQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bjf
 * @date 2017/11/27
 */
@Service
@Slf4j
public class SysRoleService extends BaseService<SysRoleMapper, SysRole, SysRoleQuery> {

    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    protected LambdaQueryWrapper<SysRole> buildQuery(SysRoleQuery q) {
        if (q == null) {
            return null;
        }
        LambdaQueryWrapper<SysRole> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.isNotBlank(q.getCode()), SysRole::getCode, q.getCode());
        qw.eq(StringUtils.isNotBlank(q.getRoleName()), SysRole::getRoleName, q.getRoleName());
        qw.in(!CollectionUtils.isEmpty(q.getRoleIdList()), SysRole::getId, q.getRoleIdList());
        return qw;
    }

    /**
     * 查询用户角色
     */
    @Cacheable(value = Names.SYS, key = "'live:role:listByUser:' + #sysUserId")
    public List<SysRole> listByUser(long sysUserId) {
        SysUserRoleQuery query = new SysUserRoleQuery().setSysUserId(sysUserId);
        List<SysUserRole> userRoles = userRoleService.listAll(query);
        if (userRoles.isEmpty()) {
            return Collections.emptyList();
        }

        SysRoleQuery q = new SysRoleQuery();
        q.setRoleIdList(userRoles.stream().map(SysUserRole::getSysRoleId).collect(Collectors.toList()));

        return this.listAll(q);
    }

}
